package com.ruiyian.common.listener;

import com.ruiyian.common.constant.Constants;
import com.ruiyian.common.utils.file.FileUtils;
import com.ruiyian.project.predict.service.PredictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * @author chong
 * @email 673426164@qq.com
 * @create 2022/1/1
 * Desc: 仿真 初始化文件消息
 */
@Slf4j
@Component
public class StartListenter implements ApplicationRunner {
    @Value("${simulation.readPath}")
    private String readMsgPath;
    @Autowired
    private PredictService predictService;

    /**
     * 监听文件消息
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String path = readMsgPath + "/msg";
        log.info("监听文件夹事件开启: "+path);
        File file = new File(path);
        if(!file.exists()){
            log.error("消息文件夹不存在");
            return;
        }
        try {
            // 初始化查询msg文件下的消息文件,并保存,删除
            List<String> fileList = FileUtils.getFileList(path);
            if(fileList!=null && fileList.size()>0){
                for(String str: fileList){
                    if(str.indexOf(Constants.SIMU)!=-1){
                        predictService.saveSimuMsg(path+"/"+str);
                    }else if(str.indexOf(Constants.RECORD)!=-1){
                        predictService.saveRecordMsg(path+"/"+str);
                    }
                }
            }
        } catch (Exception e) {
            log.error("初始化消息文件异常e={}",e.getMessage());
        }
        // 监听msg文件夹下变化
        ResourceListener.addListener(path);
    }
}
